package middleware

import (
	"gitee.com/chejiangyi/bsfgo/core/base2"
	"gitee.com/chejiangyi/bsfgo/core/utils"
	"gitee.com/chejiangyi/bsfgo/gin2/utils2"
	"github.com/gin-gonic/gin"
	"net/http"
)

var GlobalErrMsg = "全局异常拦截:发现系统级错误"

type GlobalErrorMiddleware struct{}

func (*GlobalErrorMiddleware) GetOrder() float64 {
	return -98
}
func (m *GlobalErrorMiddleware) Enabled() bool {
	return base2.BsfConfigInstance.GetGlobalErrorEnabled()
}
func (*GlobalErrorMiddleware) Middleware(r *gin.Engine) {
	r.Use(func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				utils.LogUtil.Error2("【严重错误】全局异常拦截到未处理的异常信息【接口访问异常】%v\r\n【参数信息】%v\r\n【错误详情】%v",
					c.Request.URL.Path, utils2.WebUtil.GetRequestInfo(c), err)
				if utils2.WebUtil.HeaderContentTypeIsJson(c) {
					c.AbortWithStatusJSON(http.StatusInternalServerError, base2.NewErrorApiResponseEntity[any](GlobalErrMsg))
				} else {
					utils2.WebUtil.AbortResponseText(c, http.StatusInternalServerError, GlobalErrMsg)
				}
			}
		}()
		c.Next()
		// 处理普通错误
		if len(c.Errors) > 0 {
			for _, ginErr := range c.Errors {
				// 记录错误日志
				utils.LogUtil.Error2("[全局异常拦截] %+v", ginErr.Err)
			}
			if utils2.WebUtil.HeaderContentTypeIsJson(c) {
				c.AbortWithStatusJSON(http.StatusInternalServerError, base2.NewErrorApiResponseEntity[any](GlobalErrMsg))
			} else {
				utils2.WebUtil.AbortResponseText(c, http.StatusInternalServerError, GlobalErrMsg)
			}
		}
	})
	utils.LogUtil.Info("GlobalErrorMiddleware已开启,支持全局错误拦截")
}
